package com.ys.service.storage.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.dto.EditDto;
import com.ys.entity.base.CheckByGrid;
import com.ys.entity.finance.TcwAccountDetailedForCompany;
import com.ys.entity.storage.*;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsCol;
import com.ys.enume.base.TransactionTypeEnum;
import com.ys.enume.finance.TcwOperateFrozenRunningEnum;
import com.ys.enume.storage.*;
import com.ys.mapper.storage.*;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.service.finance.TcwAccountCountForCompanyService;
import com.ys.service.storage.FbaInboundApiService;
import com.ys.service.storage.TccFbaCancelService;
import com.ys.service.storage.TccStockControlService;
import com.ys.service.sys.CommonApiService;
import com.ys.util.CheckUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

//FBA取消单
@Service("tccFbaCancelService")
public class TccFbaCancelServiceImpl implements TccFbaCancelService {
	private static final Logger logger = LoggerFactory.getLogger(TccFbaCancelServiceImpl.class);

	@Autowired
	private TccFbaCancelMapper tccFbaCancelMapper;

	@Autowired
	private TccFbaPlanMapper tccFbaPlanMapper;

	@Autowired
	private TccFbaBoxUpMapper tccFbaBoxUpMapper;

	@Autowired
	private TccFbaDeliverMapper tccFbaDeliverMapper;

	@Autowired
	private CommonApiService<TccFbaCancel> commonApiService;

	@Autowired
	private FbaInboundApiService fbaInboundApiService;

	@Autowired
	private TcwAccountCountForCompanyService tcwAccountCountForCompanyService;

	@Autowired
	private TccStockControlService tccStockControlService;

	@Autowired
	private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;

	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private StorageMapper storageMapper;

	private long menuId = MenuId.TCC_FbaCancel;


	/**
	 * 取消确认保存
	 * @param params 取消参数
	 */
	@Override
	@Transactional(propagation= Propagation.REQUIRES_NEW)
	public R passCancel(Map<String, Object> params) throws Exception{
		logger.info("FBA取消确认保存传参:"+params);
		//参数验证
		String errorBack = checkParamsDoCancel(params);
		if(errorBack!=null && !"".equals(errorBack)){
			return R.error(errorBack);
		}
		//获取数据
		int formType = Integer.parseInt(params.get("formType").toString());//表单类型
		//TODO 计划单取消
		if(formType == TccFbaDoCancelEnum.FormType.TCC_FbaPlan.value){

		}else if(formType == TccFbaDoCancelEnum.FormType.TCC_FbaDeliver.value || formType == TccFbaDoCancelEnum.FormType.TCC_FbaDeliverWc.value){
			// 发货单取消
			R res = doCancelByFbaDeliver(params);
			if(res.getCode().equals(R.Code.FAILED.value)){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return res;
			}else {
				addCancelRecord(params,false,null);
			}
		}

		return R.ok(EditDto.closeAndReload());
	}


	//记录取消时填写的数据
	public void addCancelRecord(Map<String, Object> params,boolean hasSubInfo,List<Map<String, Object>> subDataList){
		try {
			TccFbaCancel tccFbaCancel = new TccFbaCancel();
			if(checkUtil.isNotNullByObject(params.get("formType")))tccFbaCancel.setFormType(Integer.parseInt(params.get("formType").toString()));//表单类型
			if(checkUtil.isNotNullByObject(params.get("isOriginallyChw"))){
				int isOriginallyChw = Integer.parseInt(params.get("isOriginallyChw").toString());//是否原货位 0否1是
				tccFbaCancel.setIsOriginallyChw(isOriginallyChw);//是否原货位 0否1是
				String chw = "";//货位编码
				if(isOriginallyChw == 0 && checkUtil.isNotNullByObject(params.get("chw"))){
					tccFbaCancel.setChw(params.get("chw").toString());
					//通过货位编码查询信息
					Map<String,Object> tccLocationMap = new TccLocation()
							.setChw(chw)
							.addLeftJoin("TCC_WarehouseArea B ON B.Ckq = A.Ckq")//库区
							.addLeftJoin("TCC_Warehouse C ON C.Cck = B.Cck")//仓库
							.setFields("C.Vck vck, B.Vkq vkq, A.Vhw vhw")
							.queryFirstMap();
					if(tccLocationMap!=null){
						if(checkUtil.isNotNullByObject(tccLocationMap.get("vhw"))) tccFbaCancel.setVhw(tccLocationMap.get("vhw").toString());
						if(checkUtil.isNotNullByObject(tccLocationMap.get("vkq"))) tccFbaCancel.setVkq(tccLocationMap.get("vkq").toString());
						if(checkUtil.isNotNullByObject(tccLocationMap.get("vck"))) tccFbaCancel.setVck(tccLocationMap.get("vck").toString());
					}
				}
			}

			if(checkUtil.isNotNullByObject(params.get("skuAmount"))) tccFbaCancel.setSkuAmount(new BigDecimal(params.get("skuAmount").toString()));//按SKU计费标准
			if(checkUtil.isNotNullByObject(params.get("boxAmount"))) tccFbaCancel.setBoxAmount(new BigDecimal(params.get("boxAmount").toString()));//按箱计费标准
			tccFbaCancel.setStatus(1);
			if(hasSubInfo){//带子列表
				//bidFbaPlan 计划单号

				//子列表
				//装箱单号 bid
				//货件状态 boxState
				//unifiedAmount 整单计费
				//amountExplain 计费说明
				if(subDataList!=null && subDataList.size()>0){
					for(Map<String, Object> item:subDataList){
						TccFbaCancel tccFbaCancelBySub = new TccFbaCancel();
						tccFbaCancelBySub.setFormType(tccFbaCancel.getFormType());
						tccFbaCancelBySub.setIsOriginallyChw(tccFbaCancel.getIsOriginallyChw());
						tccFbaCancelBySub.setChw(tccFbaCancel.getChw());
						tccFbaCancelBySub.setVhw(tccFbaCancel.getVhw());
						tccFbaCancelBySub.setVkq(tccFbaCancel.getVkq());
						tccFbaCancelBySub.setVck(tccFbaCancel.getVck());
						tccFbaCancelBySub.setSkuAmount(tccFbaCancel.getSkuAmount());
						tccFbaCancelBySub.setBoxAmount(tccFbaCancel.getBoxAmount());
						if(checkUtil.isNotNullByObject(params.get("bidFbaPlan")))tccFbaCancelBySub.setBidFbaPlan(params.get("bidFbaPlan").toString());//计划单号
						if(checkUtil.isNotNullByObject(item.get("bid")))tccFbaCancelBySub.setBidFbaBoxUp(item.get("bid").toString());//装箱单号
						if(checkUtil.isNotNullByObject(item.get("boxState")))tccFbaCancelBySub.setBoxState(Integer.parseInt(item.get("boxState").toString()));//货件状态
						if(checkUtil.isNotNullByObject(item.get("unifiedAmount")))tccFbaCancelBySub.setUnifiedAmount(new BigDecimal(params.get("unifiedAmount").toString()));//整单计费
						if(checkUtil.isNotNullByObject(item.get("amountExplain")))tccFbaCancelBySub.setAmountExplain(item.get("amountExplain").toString());//计费说明
						tccFbaCancelMapper.insert(tccFbaCancelBySub);
					}
				}
			}else {
				//计划单号 bid
				if(checkUtil.isNotNullByObject(params.get("unifiedAmount"))) tccFbaCancel.setUnifiedAmount(new BigDecimal(params.get("unifiedAmount").toString()));//整单计费
				if(checkUtil.isNotNullByObject(params.get("amountExplain"))) tccFbaCancel.setAmountExplain(params.get("amountExplain").toString());//计费说明
				if(checkUtil.isNotNullByObject(params.get("bid"))) tccFbaCancel.setBidFbaPlan(params.get("bid").toString());//计划单号

				tccFbaCancelMapper.insert(tccFbaCancel);
			}
		}catch (Exception e) {
			logger.error("记录计划取消时填写的数据出错："+e.getMessage(),e);
		}

	}


	/**
	 * 取消确认保存-FBA计划取消带子列表
	 * @param params 取消参数
	 */
	@Override
	@Transactional(propagation= Propagation.REQUIRES_NEW)
	public R passCancelWithGrid(Map<String, Object> params) throws Exception{
		logger.info("FBA取消确认保存传参:"+params);
		List<Map<String, Object>> subDataList = new ArrayList<>();
		//参数验证
		CheckByGrid checkByGrid = checkParamsDoCancelByBoxUp(params);
		if(checkUtil.isNotNullByObject(checkByGrid.getErrMsg())){
			return R.error(checkByGrid.getErrMsg());
		}

		subDataList = checkByGrid.getSubDataList();
		//获取数据
		int formType = Integer.parseInt(params.get("formType").toString());//表单类型

		//装箱单取消
		if(formType == TccFbaDoCancelEnum.FormType.TCC_FbaBoxUp.value){
			R res = doCancelByBoxUp(params,subDataList);
			if(res.getCode().equals(R.Code.FAILED.value)){
				return res;
			}else {
				addCancelRecord(params,true,subDataList);
			}
		}

		return R.ok(EditDto.closeAndReload());
	}

	//发货单取消
	public R doCancelByFbaDeliver(Map<String, Object> params) throws Exception {
		//获取数据
		String bidFbaPlan = params.get("bid").toString();//计划单号
		int isOriginallyChw = Integer.parseInt(params.get("isOriginallyChw").toString());//是否原货位 0否1是
		String chw = "";//货位编码
		if(isOriginallyChw == 0){
			chw = params.get("chw").toString();
		}
		BigDecimal skuAmount = new BigDecimal(params.get("skuAmount").toString());//按SKU计费标准
		BigDecimal boxAmount = new BigDecimal(params.get("boxAmount").toString());//按箱计费标准

		TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(bidFbaPlan).queryFirst();
		if(tccFbaPlan==null || tccFbaPlan.getId()==null){
			return R.error("未查询到计划单信息！");
		}
//		if (tccFbaPlan.getStatus() == TccFbaPlanEnum.Status.CANCELED.value){
//			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//			return R.error("该计划单:"+tccFbaPlan.getBid()+"已取消,请核实数据");
//		}

		List<TccFbaPlanItem> tccFbaPlanItemList = new TccFbaPlanItem().setBidFbaPlan(bidFbaPlan).queryList();
		if(tccFbaPlanItemList==null || tccFbaPlanItemList.size()<=0){
			return R.error("未查询到计划单信息！");
		}

//		Integer count = new TccFbaDeliver().setFbaPlanBid(tccFbaPlan.getBid()).where("(A.status = 4 OR A.status = 5 OR A.status = 3)").count();
//		if (count != 0){
//			return R.error("选择数据不允许已转运以外的状态取消！");
//		}

		List<TccFbaBoxUp> tccFbaBoxUpList = new TccFbaBoxUp()
				.setBidFbaPlan(tccFbaPlan.getBid())
				.queryList();
		if(tccFbaBoxUpList==null || tccFbaBoxUpList.size()<=0){
			return R.error("未查询到装箱单信息！");
		}

		Date theDate = new Date();
		logger.info("********** 开始发货单取消计划单号："+tccFbaPlan.getBid()+"；"+ShiroUtils.getUserId());

		tccFbaPlan.setStatus(TccFbaPlanEnum.Status.CANCELED.value);
		tccFbaPlanMapper.update(tccFbaPlan);


		//修改状态
		for(TccFbaBoxUp tccFbaBoxUp:tccFbaBoxUpList){
			tccFbaBoxUp.setBoxState(TccFbaBoxUpEnum.BoxState.YES_CANCEL.value);
			tccFbaBoxUpMapper.update(tccFbaBoxUp);
		}

		//1、********** 计划单资金解冻 **********
		{
			TccFbaFeeDetails tccFbaFeeDetails = new TccFbaFeeDetails().setSourceBid(tccFbaPlan.getBid()).setSourceType(TccFbaLogisticsMethodEnum.SourceType.FBAPLAN.value).queryFirst();
			if (tccFbaFeeDetails.getPriceTranPredict().compareTo(BigDecimal.ZERO) != 0){
				//解冻计划单的预估物流费用金额
				logger.info("FBA发货单计划取消资金解冻："+tccFbaPlan.getVgsbm()+"；金额="+tccFbaFeeDetails.getPriceTranPredict());
				//解冻资金
				tcwAccountCountForCompanyService.thaw(
						tccFbaPlan.getVgsbm(),
						tccFbaFeeDetails.getPriceTranPredict(),
						TcwOperateFrozenRunningEnum.DocumentType.TCC_FbaPlan.value,
						tccFbaFeeDetails.getId(),
						tccFbaPlan.getBid(),
						tccFbaPlan.getBid()
				);
			}
		}

		int formType = Integer.parseInt(params.get("formType").toString());//表单类型

		//2、********** 计划单原库存解冻 **********
		{
			if (formType == TccFbaDoCancelEnum.FormType.TCC_FbaDeliver.value) {
				for (TccFbaPlanItem tccFbaPlanItem : tccFbaPlanItemList) {
					logger.info("计划单库存解冻：库存id=" + tccFbaPlanItem.getStockControlId() + "；数量=" + tccFbaPlanItem.getNumPlanDeliver());
					//解冻
					tccStockControlService.thaw(
							tccFbaPlanItem.getStockControlId(),
							tccFbaPlanItem.getNumPlanDeliver(),
							TccStockFrozenRunningEnum.SourceType.TCC_DELIVER_FINISH.value,
							tccFbaPlan.getBid(),
							tccFbaPlan.getId());
				}
			}
		}

		//3、********** 原库存出库 **********
		{
			if(isOriginallyChw == 0){//是否原货位 0否1是
				if (formType == TccFbaDoCancelEnum.FormType.TCC_FbaDeliver.value) {
					for (TccFbaPlanItem tccFbaPlanItem : tccFbaPlanItemList) {

						//出库
						String remark1 = "FBA计划单号" + tccFbaPlan.getBid() + "出库FBA装箱数量" + tccFbaPlanItem.getNumPlanDeliver();
						Integer numOut = tccFbaPlanItem.getNumPlanDeliver();
						Integer source = TccStockSourceEnum.Source.TCC_FbaBoxUp.value;
						logger.info("原库存出库：库存id=" + tccFbaPlanItem.getStockControlId() + "；数量=" + numOut);
						R r = tccStockControlService.outWithRunning(
								tccFbaPlanItem.getStockControlId(),
								remark1,
								numOut,
								tccFbaPlan.getBid(),
								source,
								tccFbaPlan.getId()
						);
						if (r.getCode() != 0) {
							TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
							return R.error(r.getMsg());
						}
					}
				}
			}

		}

		//4、********** 入库到新货位 **********
		{
			if(isOriginallyChw == 0){//是否原货位 0否1是
				for (TccFbaPlanItem tccFbaPlanItem : tccFbaPlanItemList){
					//获取原货位信息
					TccStockControl tccStockControl = new TccStockControl().setId(tccFbaPlanItem.getStockControlId()).queryFirst();
					//计算采购总价
					BigDecimal purchaseTotalPriceAll = BigDecimal.ZERO;
					if(tccStockControl.getPurchasePrice()!=null && tccFbaPlanItem.getNumPlanDeliver()!=null){
						purchaseTotalPriceAll = tccStockControl.getPurchasePrice().multiply(new BigDecimal(tccFbaPlanItem.getNumPlanDeliver()));
					}
					R r = tccStockControlService.inWithRunning(
							tccStockControl.getRkBid(),//入库单号
							chw,//货位编码
							tccStockControl.getProductName(),//商品名称
							tccFbaPlanItem.getNumPlanDeliver(),//可用数量
							tccStockControl.getProductCode(),//商品编码
							tccFbaPlanItem.getNumPlanDeliver(),//商品总数量
							tccStockControl.getPurchasePrice(),//采购单价
							purchaseTotalPriceAll,//采购总价
							BigDecimal.ZERO,//调拨单价
							BigDecimal.ZERO,//调拨总价
							tccStockControl.getVgsbm(),//公司编码
							tccStockControl.getDrksj(),//入库时间 20250412 延续之前的入库时间
							tccStockControl.getIsParent(),//是否母件
							tccFbaPlanItem.getBidFbaPlan(),//来源单号
							TccStockSourceEnum.Source.TCC_FbaBoxUp.value ,//来源类型
							"FBA发货单计划取消："+tccFbaPlanItem.getBidFbaPlan(), //流水备注
							tccStockControl.getCompanyVid() ,//所属公司
							"",//组装单号
							tccFbaPlan.getId()//来源id
					);
					logger.info("入库到新货位：入库返回="+r+"；数量="+tccFbaPlanItem.getNumPlanDeliver());
					if (r.getCode() != 0){
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return R.error(r.getMsg());
					}
				}

			}
		}

		// 查询发货单审核的贴标费用,返还

		//5、********** 费用收取： 仓储服务→手续费 **********
		{
			BigDecimal totalAmountTol = BigDecimal.ZERO;
			List<TccFbaDeliver> tccFbaDeliverList = new TccFbaDeliver().setFbaPlanBid(tccFbaPlan.getBid()).queryList();
			for (TccFbaDeliver tccFbaDeliver1 : tccFbaDeliverList) {
				if (formType == TccFbaDoCancelEnum.FormType.TCC_FbaDeliver.value){
					tccFbaDeliver1.setStatus(TccFbaDeliverEnum.Status.CANCEL.value);
				}else {
					tccFbaDeliver1.setStatus(TccFbaDeliverEnum.Status.COMPLETECANCEL.value);
				}
				tccFbaDeliverMapper.update(tccFbaDeliver1);

				if (formType == TccFbaDoCancelEnum.FormType.TCC_FbaDeliverWc.value){
					List<TcwAccountDetailedForCompany> flowList = new TcwAccountDetailedForCompany()
							.setMbid(tccFbaDeliver1.getBid())
					.queryList();
					for (TcwAccountDetailedForCompany item : flowList) {
						if (item.getVjylx().equals("仓储服务→透明计划贴标费") || item.getVjylx().equals("仓储服务→欧代贴标费") || item.getVjylx().equals("仓储服务→纸箱费")
								|| item.getVjylx().equals("物流服务→头程运费")) {
							if(item.getFje().compareTo(BigDecimal.ZERO)!=0){
								tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
										item.getVgsbm(), item.getVgsjc(),
										item.getVgsbmp(), item.getVgsjcp(),
										item.getVjylx(),
										BigDecimal.ZERO.subtract(item.getFje()),
										item.getDjysj(),
										item.getDshsj(),
										"，【FBA计划取消返还】FBA计划单号：" + tccFbaPlan.getBid() + ",FBA发货单号:" + tccFbaDeliver1.getBid(), tccFbaDeliver1.getBid(),
										item.getWriteTime());
							}

						}
					}
				}
			}

			//箱数
			BigDecimal totalBoxNum = BigDecimal.ZERO;
			//商品数
			BigDecimal productNum = BigDecimal.ZERO;

			BigDecimal unifiedAmount = new BigDecimal(params.get("unifiedAmount").toString());//整单计费

			for(TccFbaBoxUp tccFbaBoxUp:tccFbaBoxUpList){
				//获取装箱单商品信息
				List<TccFbaBoxUpItem> itemList = new TccFbaBoxUpItem().setBidBoxUp(tccFbaBoxUp.getBid()).queryList();

				for(TccFbaBoxUpItem item:itemList){
					int planBoxUpNum = item.getPlanBoxUpNum();
					List<TccFbaPlanItem> tccFbaPlanItemListNew = tccFbaPlanItemList.stream()
							.filter(tccFbaPlanItem -> tccFbaPlanItem.getId().equals(item.getFbaPlanItemId()))
							.collect(Collectors.toList());
					TccFbaPlanItem tccFbaPlanItem = tccFbaPlanItemListNew.get(0);
					//商品标
					productNum = productNum.add(new BigDecimal(planBoxUpNum));

				}
				totalBoxNum = totalBoxNum.add(new BigDecimal(tccFbaBoxUp.getBoxNum()));//箱子数
			}

			logger.info("费用收取： 仓储服务→手续费：箱数=" + totalBoxNum);
			logger.info("费用收取： 仓储服务→手续费：商品数=" + productNum);
			//按箱收费*箱数
			BigDecimal boxAmountTotal = boxAmount.multiply(totalBoxNum);
			logger.info("费用收取： 仓储服务→手续费：按箱收费*箱数=" + boxAmount);
			//按SKU收费*商品数
			BigDecimal skuAmountTotal = skuAmount.multiply(productNum);
			logger.info("费用收取： 仓储服务→手续费：按SKU收费*商品数=" + skuAmount);
			//总费用
			BigDecimal totalAmount = boxAmountTotal.add(skuAmountTotal).add(unifiedAmount);
			logger.info("费用收取： 仓储服务→手续费：总费用=" + totalAmount);
			totalAmountTol = totalAmountTol.add(totalAmount);

			String amountExplain = "";//计费说明
			if (checkUtil.isNotNullByObject(params.get("amountExplain").toString())) {
				amountExplain = params.get("amountExplain").toString();
			}

			String hjzt = "";
			if (formType == TccFbaDoCancelEnum.FormType.TCC_FbaDeliver.value){
				hjzt= TccFbaDeliverEnum.Status.NOTRANSSHIPPED.name;
			}else {
				hjzt= TccFbaDeliverEnum.Status.TRANSSHIPPED.name;
			}

			String remark = "【FBA计划取消】FBA计划单号" + tccFbaPlan.getBid()
					+ "，货件状态" + hjzt
					+ "，计费说明：" + amountExplain + ";按SKU计费标准:" + skuAmount + "；按箱计费标准：" + boxAmount + ";";
			//收取物流费用(业务交易流水)
			if(totalAmountTol.compareTo(BigDecimal.ZERO)!=0){
				R res1 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
						tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(),
						"GS0608", "仓储部",
						TransactionTypeEnum.BusinessType.CCFW_SXF.name,
						totalAmountTol.negate(),
						theDate,
						theDate,
						remark,
						tccFbaPlan.getBid(),
						theDate
				);
				if (res1.getCode().equals(R.Code.FAILED.value)) {//失败
					logger.info("新增业务交易流水失败:" + res1.getMsg());
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return R.error("新增业务交易流水失败:" + res1.getMsg());
				}

				//收取物流费用(业务交易流水)
				R res2 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
						"GS0608", "仓储部",
						tccFbaPlan.getVgsbm(), tccFbaPlan.getVgsJc(),
						TransactionTypeEnum.BusinessType.CCFW_SXF.name,
						totalAmountTol,
						theDate,
						theDate,
						remark,
						tccFbaPlan.getBid(),
						theDate
				);
				if (res2.getCode().equals(R.Code.FAILED.value)) {//失败
					logger.info("新增业务交易流水失败:" + res2.getMsg());
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return R.error("新增业务交易流水失败:" + res2.getMsg());
				}
			}

		}
		//7、********** api取消 **********
		if(tccFbaPlan.getCreationMethod()==1 ){//自动
			R apiRes = fbaInboundApiService.cancelInboundPlan(tccFbaPlan);
			if (apiRes.getCode() != 0){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return R.error("计划取消API失败,失败原因:" + apiRes.getMsg());
			}
		}
		int i = 1/0;
		return R.ok();
	}



	//装箱单取消
	public R doCancelByBoxUp(Map<String, Object> params,List<Map<String, Object>> subDataList) throws Exception {
		logger.info("********** 开始取消计划单传参：params："+params+"；\nsubDataList："+subDataList);
		//获取数据
		String bidFbaPlan = params.get("bidFbaPlan").toString();//计划单号
		int isOriginallyChw = Integer.parseInt(params.get("isOriginallyChw").toString());//是否原货位 0否1是
		String chw = "";//货位编码
		if(isOriginallyChw == 0){
			chw = params.get("chw").toString();
		}
		BigDecimal skuAmount = new BigDecimal(params.get("skuAmount").toString());//按SKU计费标准
		BigDecimal boxAmount = new BigDecimal(params.get("boxAmount").toString());//按箱计费标准

		TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(bidFbaPlan).queryFirst();
		if(tccFbaPlan==null || tccFbaPlan.getId()==null){
			return R.error("未查询到计划单信息！");
		}
		List<TccFbaPlanItem> tccFbaPlanItemList = new TccFbaPlanItem().setBidFbaPlan(bidFbaPlan).queryList();
		if(tccFbaPlanItemList==null || tccFbaPlanItemList.size()<=0){
			return R.error("未查询到计划单信息！");
		}

		List<TccFbaBoxUp> tccFbaBoxUpList = new TccFbaBoxUp()
				.setBidFbaPlan(tccFbaPlan.getBid())
				.queryList();
		if(tccFbaBoxUpList==null || tccFbaBoxUpList.size()<=0){
			return R.error("未查询到装箱单信息！");
		}
		Date theDate = new Date();
		logger.info("********** 开始取消计划单号："+tccFbaPlan.getBid()+"；"+ShiroUtils.getUserId());



		//修改状态
		for(TccFbaBoxUp tccFbaBoxUp:tccFbaBoxUpList){
			tccFbaBoxUp.setBoxState(TccFbaBoxUpEnum.BoxState.YES_CANCEL.value);
			tccFbaBoxUpMapper.update(tccFbaBoxUp);
		}

		//1、********** 计划单资金解冻 **********
		{
			TccFbaFeeDetails tccFbaFeeDetails = new TccFbaFeeDetails().setSourceBid(tccFbaPlan.getBid()).setSourceType(TccFbaLogisticsMethodEnum.SourceType.FBAPLAN.value).queryFirst();
			if (tccFbaFeeDetails.getPriceTranPredict().compareTo(BigDecimal.ZERO) != 0){
				//解冻计划单的预估物流费用金额
				logger.info("计划单资金解冻："+tccFbaPlan.getVgsbm()+"；金额="+tccFbaFeeDetails.getPriceTranPredict());
				//解冻资金
				tcwAccountCountForCompanyService.thaw(
						tccFbaPlan.getVgsbm(),
						tccFbaFeeDetails.getPriceTranPredict(),
						TcwOperateFrozenRunningEnum.DocumentType.TCC_FbaPlan.value,
						tccFbaFeeDetails.getId(),
						tccFbaPlan.getBid(),
						tccFbaPlan.getBid()
				);
			}
		}

		//2、********** 计划单原库存解冻 **********
		{
			for (TccFbaPlanItem tccFbaPlanItem : tccFbaPlanItemList){
				logger.info("计划单库存解冻：库存id="+tccFbaPlanItem.getStockControlId()+"；数量="+tccFbaPlanItem.getNumPlanDeliver());
				//解冻
				tccStockControlService.thaw(
						tccFbaPlanItem.getStockControlId(),
						tccFbaPlanItem.getNumPlanDeliver(),
						TccStockFrozenRunningEnum.SourceType.TCC_FBABOXUP_CANCEL_JD.value,
						tccFbaPlan.getBid(),
						tccFbaPlan.getId());
			}
		}

		//3、********** 原库存出库 **********
		{
			if(isOriginallyChw == 0){//是否原货位 0否1是
				for (TccFbaPlanItem tccFbaPlanItem : tccFbaPlanItemList){

					//出库
					String remark1 = "FBA计划单号"+tccFbaPlan.getBid() + "出库FBA装箱数量"+tccFbaPlanItem.getNumPlanDeliver();
					Integer numOut = tccFbaPlanItem.getNumPlanDeliver();
					Integer source = TccStockSourceEnum.Source.TCC_FbaBoxUp.value;
					logger.info("原库存出库：库存id="+tccFbaPlanItem.getStockControlId()+"；数量="+numOut);
					R r = tccStockControlService.outWithRunning(
							tccFbaPlanItem.getStockControlId(),
							remark1,
							numOut,
							tccFbaPlan.getBid(),
							source,
							tccFbaPlan.getId()
					);
					if (r.getCode() != 0){
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return R.error(r.getMsg());
					}
				}
			}

		}

		//4、********** 入库到新货位 **********
		{
			if(isOriginallyChw == 0){//是否原货位 0否1是
				for (TccFbaPlanItem tccFbaPlanItem : tccFbaPlanItemList){
					//获取原货位信息
					TccStockControl tccStockControl = new TccStockControl().setId(tccFbaPlanItem.getStockControlId()).queryFirst();
					//计算采购总价
					BigDecimal purchaseTotalPriceAll = BigDecimal.ZERO;
					if(tccStockControl.getPurchasePrice()!=null && tccFbaPlanItem.getNumPlanDeliver()!=null){
						purchaseTotalPriceAll = tccStockControl.getPurchasePrice().multiply(new BigDecimal(tccFbaPlanItem.getNumPlanDeliver()));
					}
					R r = tccStockControlService.inWithRunning(
							tccStockControl.getRkBid(),//入库单号
							chw,//货位编码
							tccStockControl.getProductName(),//商品名称
							tccFbaPlanItem.getNumPlanDeliver(),//可用数量
							tccStockControl.getProductCode(),//商品编码
							tccFbaPlanItem.getNumPlanDeliver(),//商品总数量
							tccStockControl.getPurchasePrice(),//采购单价
							purchaseTotalPriceAll,//采购总价
							BigDecimal.ZERO,//调拨单价
							BigDecimal.ZERO,//调拨总价
							tccStockControl.getVgsbm(),//公司编码
							tccStockControl.getDrksj(),//new Date(),//入库时间
							tccStockControl.getIsParent(),//是否母件
							tccFbaPlanItem.getBidFbaPlan(),//来源单号
							TccStockSourceEnum.Source.TCC_FbaBoxUp.value ,//来源类型
							"FBA装箱单计划取消："+tccFbaPlanItem.getBidFbaPlan(), //流水备注
							tccStockControl.getCompanyVid() ,//所属公司
							"",//组装单号
							tccFbaPlan.getId()//来源id
					);
					logger.info("入库到新货位：入库返回="+r+"；数量="+tccFbaPlanItem.getNumPlanDeliver());
					if (r.getCode() != 0){
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return R.error(r.getMsg());
					}
				}

			}
		}

		//5、********** 费用收取： 仓储服务→手续费 **********
		{

			for(TccFbaBoxUp tccFbaBoxUp:tccFbaBoxUpList){
				String bid = tccFbaBoxUp.getBid();//单号
				Map<String, Object> subInfo = subDataList.stream().filter(e->e.get("bid").toString().equals(bid)).collect(Collectors.toList()).get(0);

				BigDecimal unifiedAmount = new BigDecimal(subInfo.get("unifiedAmount").toString());//整单计费
				String amountExplain = "";//计费说明
				if(checkUtil.isNotNullByObject(subInfo.get("amountExplain"))){
					amountExplain = subInfo.get("amountExplain").toString();
				}

				//箱数
				BigDecimal totalBoxNum = new BigDecimal(tccFbaBoxUp.getBoxNum());
				//商品数
				BigDecimal productNum = BigDecimal.ZERO;

				//获取装箱单商品信息
				List<TccFbaBoxUpItem> tccFbaBoxUpItemList = new TccFbaBoxUpItem().setBidBoxUp(bid).queryList();
				for (TccFbaBoxUpItem tccFbaBoxUpItem : tccFbaBoxUpItemList){
					if(tccFbaBoxUp.getBoxState().equals(TccFbaBoxUpEnum.BoxState.YES_UP.value)){//已装箱
						productNum = productNum.add(new BigDecimal(tccFbaBoxUpItem.getRealityBoxUpNum()));
					}else {
						productNum = productNum.add(new BigDecimal(tccFbaBoxUpItem.getPlanBoxUpNum()));
					}
				}

				logger.info("费用收取： 仓储服务→手续费：箱数="+totalBoxNum);
				logger.info("费用收取： 仓储服务→手续费：商品数="+productNum);
				//按箱收费*箱数
				BigDecimal boxAmountTotal = boxAmount.multiply(totalBoxNum);
				logger.info("费用收取： 仓储服务→手续费：按箱收费*箱数="+boxAmountTotal);
				//按SKU收费*商品数
				BigDecimal skuAmountTotal = skuAmount.multiply(productNum);
				logger.info("费用收取： 仓储服务→手续费：按SKU收费*商品数="+skuAmountTotal);
				//总费用
				BigDecimal totalAmount = boxAmountTotal.add(skuAmountTotal).add(unifiedAmount);
				logger.info("费用收取： 仓储服务→手续费：总费用="+totalAmount);

				String remark = "【FBA计划取消】FBA计划单号："+tccFbaPlan.getBid()
						+"，FBA装箱单号："+bid
						+"，货件状态"+TccFbaBoxUpEnum.BoxState.getName(Integer.parseInt(subInfo.get("boxState").toString()))
						+"，计费说明：" + amountExplain
						+"按SKU计费标准：" + skuAmount
						+"；按箱计费标准：" + boxAmount
						+"；";
				if(totalAmount.compareTo(BigDecimal.ZERO)!=0){
					//收取物流费用(业务交易流水)
					R res1 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
							tccFbaPlan.getVgsbm(),tccFbaPlan.getVgsJc(),
							"GS0608", "仓储部",
							TransactionTypeEnum.BusinessType.CCFW_SXF.name,
							totalAmount.negate(),
							theDate,
							theDate,
							remark,
							bid,
							theDate
					);
					if(res1.getCode().equals(R.Code.FAILED.value)){//失败
						logger.info("新增业务交易流水失败:"+res1.getMsg());
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return R.error("新增业务交易流水失败:"+res1.getMsg());
					}

					//收取物流费用(业务交易流水)
					R res2 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
							"GS0608", "仓储部",
							tccFbaPlan.getVgsbm(),tccFbaPlan.getVgsJc(),
							TransactionTypeEnum.BusinessType.CCFW_SXF.name,
							totalAmount,
							theDate,
							theDate,
							remark,
							bid,
							theDate
					);
					if(res2.getCode().equals(R.Code.FAILED.value)){//失败
						logger.info("新增业务交易流水失败:"+res2.getMsg());
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
						return R.error("新增业务交易流水失败:"+res2.getMsg());
					}
				}

			}
		}


		//修改计划单状态
		tccFbaPlan.setStatus(TccFbaPlanEnum.Status.CANCELED.value);
		tccFbaPlanMapper.update(tccFbaPlan);

		//7、********** api取消 **********
		{
			if(tccFbaPlan.getCreationMethod()==1 ) {//自动
				R apiRes = fbaInboundApiService.cancelInboundPlan(tccFbaPlan);
				if (apiRes.getCode() != 0) {
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return R.error("计划取消API失败,失败原因:" + apiRes.getMsg());
				}
			}
		}
		return R.ok();
	}




	/**
	 * FBA装箱单计划取消 - 参数验证
	 */
	public CheckByGrid checkParamsDoCancelByBoxUp(Map<String, Object> params) throws Exception {
		//验证子列表数据
		CheckByGrid checkByGrid = new CheckByGrid();
		if(checkUtil.isNullByObject(params.get("isOriginallyChw"))){
			checkByGrid.setErrMsg("请选择是否原货位");
			return checkByGrid;
		}

		if(checkUtil.isNullByObject(params.get("bidFbaPlan"))){
			checkByGrid.setErrMsg("计划单号为空");
			return checkByGrid;
		}
		if(checkUtil.isNullByObject(params.get("formType"))){
			checkByGrid.setErrMsg("表单类型为空");
			return checkByGrid;
		}
		if(params.get("isOriginallyChw").toString().equals("0")){
			if(checkUtil.isNullByObject(params.get("chw"))){
				checkByGrid.setErrMsg("若不选择原货位，请选择新货位信息");
				return checkByGrid;
			}
		}
		if(checkUtil.isNullByObject(params.get("skuAmount"))){
			checkByGrid.setErrMsg("按SKU计费标准为空");
			return checkByGrid;
		}else {
			if(!checkUtil.isNumber(params.get("skuAmount").toString())){
				checkByGrid.setErrMsg("按SKU计费标准应为数字");
				return checkByGrid;
			}
		}

		if(checkUtil.isNullByObject(params.get("boxAmount"))){
			checkByGrid.setErrMsg("按箱计费标准为空");
			return checkByGrid;
		}else {
			if(!checkUtil.isNumber(params.get("boxAmount").toString())){
				checkByGrid.setErrMsg("按箱计费标准应为数字");
				return checkByGrid;
			}
		}

		String backMsg = "";
		List<Map<String, Object>> subDataList = new ArrayList<>();
		if(params.get("subData")==null){
			checkByGrid.setErrMsg("列表信息为空");
			return checkByGrid;
		}

		JSONArray subDataArray = JSON.parseArray(params.get("subData").toString());
		if(subDataArray!=null && subDataArray.size()>0){
			for (int i = 0; i < subDataArray.size(); i++) {
				JSONObject jsonObject = subDataArray.getJSONObject(i);
				Map<String, Object> paramsNewByRecord = new HashMap<>();
				for (String key : jsonObject.keySet()) {
					paramsNewByRecord.put(key, jsonObject.get(key));
				}
				subDataList.add(paramsNewByRecord);
			}
			BigDecimal subTotalPrice = BigDecimal.ZERO;
			//验证
			for(int i = 0;i<subDataList.size();i++){
				String backMsgByRow = "";
				Map<String, Object> subData = subDataList.get(i);

				if(checkUtil.isNullByObject(subData.get("bid"))){
					backMsgByRow +=  "单号为空";
				}
				if(checkUtil.isNullByObject(subData.get("unifiedAmount"))){
					backMsgByRow +=  "整单计费标准为空";
				}else {
					if(!checkUtil.isNumber(subData.get("unifiedAmount").toString())){
						backMsgByRow +=  "整单计费标准应为数字";
					}
				}

				if(checkUtil.isNotNullByObject(backMsgByRow)){
					backMsg += "列表第" + (i+1) + "行，" + backMsgByRow;
				}


				if(checkUtil.isNotNullByObject(subData.get("subTotalPrice"))){
					subTotalPrice = subTotalPrice.add(new BigDecimal(subData.get("subTotalPrice").toString()));
				}
			}

		}else{
			backMsg = "列表信息为空";
		}
		checkByGrid.setErrMsg(backMsg);
		checkByGrid.setSubDataList(subDataList);


		return checkByGrid;
	}





	/**
	 * 参数验证
	 */
	public String checkParamsDoCancel(Map<String, Object> params) throws Exception {
		if(checkUtil.isNullByObject(params.get("isOriginallyChw"))){
			return "请选择是否原货位";
		}
		if(checkUtil.isNullByObject(params.get("bid"))){
			return "单号为空";
		}
		if(checkUtil.isNullByObject(params.get("formType"))){
			return "表单类型为空";
		}
		if(params.get("isOriginallyChw").toString().equals("0")){
			if(checkUtil.isNullByObject(params.get("chw"))){
				return "若不选择原货位，请选择新货位信息";
			}
		}
		if(checkUtil.isNullByObject(params.get("skuAmount"))){
			return "按SKU计费标准为空";
		}else {
			if(!checkUtil.isNumber(params.get("skuAmount").toString())){
				return "按SKU计费标准应为数字";
			}
		}

		if(checkUtil.isNullByObject(params.get("boxAmount"))){
			return "按箱计费标准为空";
		}else {
			if(!checkUtil.isNumber(params.get("boxAmount").toString())){
				return "按箱计费标准应为数字";
			}
		}
		if(checkUtil.isNullByObject(params.get("unifiedAmount"))){
			return "整单计费标准为空";
		}else {
			if(!checkUtil.isNumber(params.get("unifiedAmount").toString())){
				return "整单计费标准应为数字";
			}
		}

		return null;
	}


//	/**
//	 * 取消确认
//	 * @param params 取消参数
//	 * @param menuId 菜单id
//	 * @param isCheck 是否验证参数
//	 * @param isDirectCancel 是否直接做取消确认
//	 */
//	@Override
//	@Transactional(propagation= Propagation.REQUIRES_NEW)
//	public R passCancel(Map<String, Object> params, Long menuId,boolean isCheck,boolean isDirectCancel) throws Exception{
//		logger.info("FBA取消确认传参:"+params);
//		if(isCheck){
//			//参数验证
//			String errorBack = checkParamsDoCancel(params, menuId);
//			if(errorBack!=null && !"".equals(errorBack)){
//				return R.error(errorBack);
//			}
//		}
//
//		//获取审核人信息
//		TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setStatus(1).queryFirst();
//		if(tsUserChange==null){
//			return R.error("未查询到审核人信息！");
//		}
//
//		TccFbaCancel tccFbaCancel = JSON.parseObject(JSON.toJSONString(params), TccFbaCancel.class);
//
//		TccFbaCancel oldInfo = new TccFbaCancel().setBid(tccFbaCancel.getBid()).queryFirst();
//		//验证状态
//		if(oldInfo.getCancelState().equals(TccFbaCancelEnum.CancelState.YES_CANCEL.value)){
//			return R.error("该取消单已取消，无需重复操作！");
//		}
//
//		tccFbaCancel.setId(oldInfo.getId());
//		tccFbaCancel.setExamineChangeId(tsUserChange.getId());//审核人
//		tccFbaCancel.setExamineTime(new Date());//审核时间
//		tccFbaCancel.setCancelState(TccFbaCancelEnum.CancelState.YES_CANCEL.value);//取消状态 ：已取消
//
//		//进行对应单据的取消
//		List<TccFbaCancelItem> itemList = new TccFbaCancelItem().setBidCancel(tccFbaCancel.getBid()).queryList();
//		//货件状态
//		int shipmentState = itemList.get(0).getShipmentState();
//		TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(oldInfo.getBidFbaPlan()).queryFirst();
//		if(tccFbaPlan==null || tccFbaPlan.getId()==null){
//			return R.error("未查询到计划单信息！");
//		}
//		List<TccFbaPlanItem> tccFbaPlanItemList = new TccFbaPlanItem().setBidFbaPlan(oldInfo.getBidFbaPlan()).queryList();
//		if(tccFbaPlanItemList==null || tccFbaPlanItemList.size()<=0){
//			return R.error("未查询到计划单信息！");
//		}
//		List<TccFbaBoxUp> tccFbaBoxUpList = new TccFbaBoxUp()
//				.addLeftJoin("TCC_FbaCancelItem B ON B.BidFbaBoxUp = A.Bid")
//				.where("B.BidCancel = '"+tccFbaCancel.getBid()+"'")
//				.queryList();
//		if(tccFbaBoxUpList==null || tccFbaBoxUpList.size()<=0){
//			return R.error("未查询到装箱单信息！");
//		}
//		Date theDate = new Date();
//		logger.info("********** 开始取消计划单号："+oldInfo.getBidFbaPlan()+"；"+ShiroUtils.getUserId());
//
//		//1、********** 计划单资金解冻 **********
//		{
//			//取消时 需要 计划单资金解冻 的状态
//			List<TccFbaCancelEnum.ShipmentState> doPlanAmountThaw = TccFbaCancelEnum.ShipmentState.doPlanAmountThaw();
//			boolean isDo = TccFbaCancelEnum.ShipmentState.stateIsPass(shipmentState,doPlanAmountThaw);
//			if(isDo){
//				TccFbaFeeDetails tccFbaFeeDetails = new TccFbaFeeDetails().setSourceBid(tccFbaPlan.getBid()).setSourceType(TccFbaLogisticsMethodEnum.SourceType.FBAPLAN.value).queryFirst();
//				if (tccFbaFeeDetails.getPriceTranPredict().compareTo(BigDecimal.ZERO) != 0){
//					logger.info("计划单资金解冻："+tccFbaPlan.getVgsbm()+"；金额="+tccFbaFeeDetails.getPriceTranPredict());
//					//解冻资金
//					tcwAccountCountForCompanyService.thaw(
//							tccFbaPlan.getVgsbm(),
//							tccFbaFeeDetails.getPriceTranPredict(),
//							TcwOperateFrozenRunningEnum.DocumentType.TCC_FbaPlan.value,
//							tccFbaFeeDetails.getId(),
//							tccFbaPlan.getBid(),
//							tccFbaPlan.getBid()
//					);
//				}
//			}
//		}
//
//		//2、********** 计划单库存解冻 **********
//		{
//			//取消时 需要 库存解冻 的状态
//			List<TccFbaCancelEnum.ShipmentState> doStockThaw = TccFbaCancelEnum.ShipmentState.doStockThaw();
//			boolean isDo = TccFbaCancelEnum.ShipmentState.stateIsPass(shipmentState,doStockThaw);
//			if(isDo){
//				for (TccFbaPlanItem tccFbaPlanItem : tccFbaPlanItemList){
//					logger.info("计划单库存解冻：库存id="+tccFbaPlanItem.getStockControlId()+"；数量="+tccFbaPlanItem.getNumPlanDeliver());
//					//解冻
//					tccStockControlService.thaw(
//							tccFbaPlanItem.getStockControlId(),
//							tccFbaPlanItem.getNumPlanDeliver(),
//							TccStockFrozenRunningEnum.SourceType.TCC_FBACANCEL_JD.value,
//							tccFbaCancel.getBid(),
//							tccFbaCancel.getId());
//				}
//			}
//		}
//
//		//3、********** 原库存出库 **********
//		{
//			//取消时 需要 原库存出库 的状态
//			List<TccFbaCancelEnum.ShipmentState> doStockOutByOld = TccFbaCancelEnum.ShipmentState.doStockOutByOld();
//			boolean isDo = TccFbaCancelEnum.ShipmentState.stateIsPass(shipmentState,doStockOutByOld);
//			if(isDo && !isDirectCancel){
//				for (TccFbaPlanItem tccFbaPlanItem : tccFbaPlanItemList){
//					//出库
//					String remark1 = "FBA取消单号：" + tccFbaCancel.getBid() + "出库FBA计划数量";
//					Integer numOut = tccFbaPlanItem.getNumPlanDeliver();
//					Integer source = TccStockSourceEnum.Source.TCC_FbaCancel.value;
//					logger.info("原库存出库：库存id="+tccFbaPlanItem.getStockControlId()+"；数量="+tccFbaPlanItem.getNumPlanDeliver());
//					R r = tccStockControlService.outWithRunning(tccFbaPlanItem.getStockControlId(), remark1, numOut, tccFbaCancel.getBid(),source,tccFbaCancel.getId());
//					if (r.getCode() != 0){
//						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//						return R.error(r.getMsg());
//					}
//				}
//			}
//		}
//
//		//4、********** 入库到新货位 **********
//		{
//			//取消时 需要 入库到新货位 的状态
//			List<TccFbaCancelEnum.ShipmentState> doStockIn = TccFbaCancelEnum.ShipmentState.doStockIn();
//			boolean isDo = TccFbaCancelEnum.ShipmentState.stateIsPass(shipmentState,doStockIn);
//			if(isDo && !isDirectCancel){
//				for (TccFbaPlanItem tccFbaPlanItem : tccFbaPlanItemList){
//					//获取原货位信息
//					TccStockControl tccStockControl = new TccStockControl().setId(tccFbaPlanItem.getStockControlId()).queryFirst();
//					//计算采购总价
//					BigDecimal purchaseTotalPriceAll = BigDecimal.ZERO;
//					if(tccStockControl.getPurchasePrice()!=null && tccFbaPlanItem.getNumPlanDeliver()!=null){
//						purchaseTotalPriceAll = tccStockControl.getPurchasePrice().multiply(new BigDecimal(tccFbaPlanItem.getNumPlanDeliver()));
//					}
//					R r = tccStockControlService.inWithRunning(
//							tccStockControl.getRkBid(),//入库单号
//							tccFbaCancel.getChw(),//货位编码
//							tccStockControl.getProductName(),//商品名称
//							tccFbaPlanItem.getNumPlanDeliver(),//可用数量
//							tccStockControl.getProductCode(),//商品编码
//							tccFbaPlanItem.getNumPlanDeliver(),//商品总数量
//							tccStockControl.getPurchasePrice(),//采购单价
//							purchaseTotalPriceAll,//采购总价
//							BigDecimal.ZERO,//调拨单价
//							BigDecimal.ZERO,//调拨总价
//							tccStockControl.getVgsbm(),//公司编码
//							new Date(),//入库时间
//							tccStockControl.getIsParent(),//是否母件
//							tccFbaCancel.getBid(),//来源单号
//							TccStockSourceEnum.Source.TCC_FbaCancel.value ,//来源类型
//							"FBA取消单："+tccFbaCancel.getBid(), //流水备注
//							tccStockControl.getCompanyVid() ,//所属公司
//							"",//组装单号
//							tccFbaPlanItem.getId()//来源id
//					);
//					logger.info("入库到新货位：入库返回="+r+"；数量="+tccFbaPlanItem.getNumPlanDeliver());
//					if (r.getCode() != 0){
//						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//						return R.error(r.getMsg());
//					}
//				}
//
//			}
//		}
//
//		//5、********** 费用收取： 仓储服务→手续费 **********
//		{
//			//取消时 需要 费用收取： 仓储服务→手续费 的状态
//			List<TccFbaCancelEnum.ShipmentState> doChargeTrouble = TccFbaCancelEnum.ShipmentState.doChargeTrouble();
//			boolean isDo = TccFbaCancelEnum.ShipmentState.stateIsPass(shipmentState,doChargeTrouble);
//			if(isDo){
//				//箱数
//				BigDecimal totalBoxNum = BigDecimal.ZERO;
//				for(TccFbaBoxUp tccFbaBoxUp:tccFbaBoxUpList){
//					totalBoxNum = totalBoxNum.add(new BigDecimal(tccFbaBoxUp.getBoxNum()));
//				}
//				//商品数
//				BigDecimal productNum = BigDecimal.ZERO;
//				for (TccFbaPlanItem tccFbaPlanItem : tccFbaPlanItemList){
//					productNum = productNum.add(new BigDecimal(tccFbaPlanItem.getNumPlanDeliver()));
//				}
//				logger.info("费用收取： 仓储服务→手续费：箱数="+totalBoxNum);
//				logger.info("费用收取： 仓储服务→手续费：商品数="+productNum);
//				//按箱收费*箱数
//				BigDecimal boxAmount = tccFbaCancel.getBoxAmount().multiply(totalBoxNum);
//				logger.info("费用收取： 仓储服务→手续费：按箱收费*箱数="+boxAmount);
//				//按SKU收费*商品数
//				BigDecimal skuAmount = tccFbaCancel.getSkuAmount().multiply(totalBoxNum);
//				logger.info("费用收取： 仓储服务→手续费：按SKU收费*商品数="+skuAmount);
//				//统一收费
//				BigDecimal unifiedAmount = tccFbaCancel.getUnifiedAmount();
//				//总费用
//				BigDecimal totalAmount = boxAmount.add(skuAmount).add(unifiedAmount);
//				logger.info("费用收取： 仓储服务→手续费：总费用="+totalAmount);
//
//				//收取物流费用(业务交易流水)
//				R res1 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
//						tccFbaPlan.getVgsbm(),tccFbaPlan.getVgsJc(),
//						"GS0608", "仓储部",
//						TransactionTypeEnum.BusinessType.CCFW_SXF.name,
//						totalAmount.negate(),
//						tccFbaCancel.getCreateTime(),
//						theDate,
//						"FAB计划单号："+tccFbaPlan.getBid(),
//						theDate
//				);
//				if(res1.getCode().equals(R.Code.FAILED.value)){//失败
//					logger.info("新增业务交易流水失败:"+res1.getMsg());
//					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//					return R.error("新增业务交易流水失败:"+res1.getMsg());
//				}
//
//				//收取物流费用(业务交易流水)
//				R res2 = tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
//						"GS0608", "仓储部",
//						tccFbaPlan.getVgsbm(),tccFbaPlan.getVgsJc(),
//						TransactionTypeEnum.BusinessType.CCFW_SXF.name,
//						totalAmount,
//						tccFbaCancel.getCreateTime(),
//						theDate,
//						"FAB计划单号："+tccFbaPlan.getBid(),
//						theDate
//				);
//				if(res2.getCode().equals(R.Code.FAILED.value)){//失败
//					logger.info("新增业务交易流水失败:"+res2.getMsg());
//					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//					return R.error("新增业务交易流水失败:"+res2.getMsg());
//				}
//			}
//		}
//
//		//6、********** 费用返还，流水返还 **********
//		{
//			//取消时 需要 费用返还，流水返 的状态
//			List<TccFbaCancelEnum.ShipmentState> doBackFlow = TccFbaCancelEnum.ShipmentState.doBackFlow();
//			boolean isDo = TccFbaCancelEnum.ShipmentState.stateIsPass(shipmentState,doBackFlow);
//			if(isDo && !isDirectCancel){
//				String searchBid = itemList.get(0).getBidFbaDelivery();
//				if(checkUtil.isNotNullByObject(searchBid)){
//					List<TcwAccountDetailedForCompany> flowList = new TcwAccountDetailedForCompany()
//							.where("A.Vbz LIKE '%"+searchBid+"%'")
//							.queryList();
//					if(flowList!=null && flowList.size()>0){
//						for(TcwAccountDetailedForCompany item:flowList){
//							tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJcNoTrigger(
//									item.getVgsbm(),item.getVgsjc(),
//									item.getVgsbmp(),item.getVgsjcp(),
//									item.getVjylx(),
//									BigDecimal.ZERO.subtract(item.getFje()),
//									item.getDjysj(),
//									item.getDshsj(),
//									"，取消单："+tccFbaCancel.getBid()+"费用返还："+item.getVbz(),
//									item.getWriteTime() );
//
//						}
//					}
//
//				}
//			}
//		}
//
//		//7、********** api取消 **********
//		{
//			R apiRes = fbaInboundApiService.cancelInboundPlan(tccFbaPlan);
//			if (apiRes.getCode() != 0){
//				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//				return R.error("计划取消API失败,失败原因:" + apiRes.getMsg());
//			}
//		}
//
//		//修改数据
//		tccFbaCancelMapper.update(tccFbaCancel);
//		logger.info("********** 完成取消计划单号："+oldInfo.getBidFbaPlan()+"；"+ShiroUtils.getUserId());
//
//		return R.ok(EditDto.closeAndReload());
//	}



//
//
//	/**
//	 * 新增FBA取消单
//	 * @param bidFbaPlan FBA计划单号【必填】
//	 * @param itemList FBA取消单详情【必填】
//	 */
//	@Override
//	//@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
//	public R addCancel(String bidFbaPlan, List<TccFbaCancelItemByAdd> itemList) throws Exception{
//		logger.info("新增FBA取消单传参：bidFbaPlan="+bidFbaPlan+"；itemList="+itemList+"；"+ShiroUtils.getUserId());
//		//获取单号信息
//		String bid = commonApiService.getCommonNextBid(menuId);
//
//		//填入
//		TccFbaCancel entity = new TccFbaCancel();
//		entity.setBid(bid);//单号
//		entity.setCancelState(TccFbaCancelEnum.CancelState.NOT_CANCEL.value);//取消状态，未取消
//		entity.setBidFbaPlan(bidFbaPlan);//FBA计划单号
//		entity.setStatus(1);
//		entity.setBoxAmount(BigDecimal.ZERO);
//		entity.setSkuAmount(BigDecimal.ZERO);
//		entity.setUnifiedAmount(BigDecimal.ZERO);
//
//		//获取制单人信息
//		TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setStatus(1).queryFirst();
//		if(tsUserChange!=null){
//			entity.setCreateChangeId(tsUserChange.getId());//制单人变更信息
//		}else {
//			return R.error("未查询到制单人信息！");
//		}
//
//
//		//新增详情信息
//		for(TccFbaCancelItemByAdd tccFbaCancelItemByAdd : itemList){
//			TccFbaCancelItem itemEntity = new TccFbaCancelItem();
//			itemEntity.setBidCancel(bid);
//			itemEntity.setShipmentState(tccFbaCancelItemByAdd.getShipmentState());
//			itemEntity.setBidFbaBoxUp(tccFbaCancelItemByAdd.getBidFbaBoxUp());
//			itemEntity.setStatus(1);
//			if(checkUtil.isNotNullByObject(tccFbaCancelItemByAdd.getBidFbaDelivery())){
//				itemEntity.setBidFbaDelivery(tccFbaCancelItemByAdd.getBidFbaDelivery());
//			}
//			tccFbaCancelItemMapper.insert(itemEntity);
//		}
//
//
//		//新增
//		tccFbaCancelMapper.insert(entity);
//		return R.ok();
//	}
//
//	//暂不取消
//	@Override
//	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
//	public R noCancel(String bid) throws Exception{
//		logger.info("FBA取消单 *暂不取消* 传参：bid="+bid+"；"+ShiroUtils.getUserId());
//		//获取原数据
//		TccFbaCancel entity = new TccFbaCancel().setBid(bid).queryFirst();
//		List<TccFbaCancelItem> itemList = new TccFbaCancelItem().setBidCancel(entity.getBid()).queryList();
//		//验证状态
//		if(entity.getCancelState().equals(TccFbaCancelEnum.CancelState.YES_CANCEL.value)){
//			return R.error("该取消单已取消，无需重复操作！");
//		}
//
//		//原单据 退回原状态
//
//		//计划单退回原状态
//		TccFbaPlan tccFbaPlan = new TccFbaPlan().setBid(entity.getBidFbaPlan()).queryFirst();
//		tccFbaPlan.setStatus(TccFbaPlanEnum.Status.ISAUDITED.value);
//		tccFbaPlanMapper.update(tccFbaPlan);
//
//		//暂不取消时 需要变更装箱单状态的 货件状态
//		List<TccFbaCancelEnum.ShipmentState> doBoxUpCancelState = TccFbaCancelEnum.ShipmentState.doBoxUpCancelState();
//		//暂不取消时 需要变更发货单状态的 货件状态
//		List<TccFbaCancelEnum.ShipmentState> doDeliverCancelState = TccFbaCancelEnum.ShipmentState.doDeliverCancelState();
//		//装箱单、发货单退回原状态
//		for(TccFbaCancelItem tccFbaCancelItem:itemList){
//			//装箱单退回原状态
//			boolean isDoBoxUp = TccFbaCancelEnum.ShipmentState.stateIsPass(tccFbaCancelItem.getShipmentState(),doBoxUpCancelState);
//			if(isDoBoxUp){
//				Integer oldState = TccFbaCancelEnum.ShipmentState.getBoxUpOldStateByShipmentState(tccFbaCancelItem.getShipmentState());
//				TccFbaBoxUp tccFbaBoxUp = new TccFbaBoxUp().setBid(tccFbaCancelItem.getBidFbaBoxUp()).queryFirst();
//				tccFbaBoxUp.setBoxState(oldState);
//				logger.info(ShiroUtils.getUserId()+" *暂不取消* 装箱单退回原状态："+tccFbaCancelItem.getBidFbaBoxUp()+"，"+TccFbaBoxUpEnum.BoxState.getName(oldState));
//				tccFbaBoxUpMapper.update(tccFbaBoxUp);
//			}
//			//发货单退回原状态
//			boolean isDoDeliver = TccFbaCancelEnum.ShipmentState.stateIsPass(tccFbaCancelItem.getShipmentState(),doDeliverCancelState);
//			if(isDoDeliver){
//				Integer oldState = TccFbaCancelEnum.ShipmentState.getDeliverOldStateByShipmentState(tccFbaCancelItem.getShipmentState());
//				TccFbaDeliver tccFbaDeliver = new TccFbaDeliver().setBid(tccFbaCancelItem.getBidFbaDelivery()).queryFirst();
//				tccFbaDeliver.setStatus(oldState);
//				logger.info(ShiroUtils.getUserId()+" *暂不取消*发货单退回原状态："+tccFbaCancelItem.getBidFbaDelivery()+"，"+oldState);
//				tccFbaDeliverMapper.update(tccFbaDeliver);
//			}
//
//			//记录日志
//			TccFbaCancelDelInfo tccFbaCancelDelInfo = new TccFbaCancelDelInfo()
//					.setCancelBid(entity.getBid())
//					.setBidFbaPlan(entity.getBidFbaPlan())
//					.setBidFbaBoxUp(tccFbaCancelItem.getBidFbaBoxUp())
//					.setBidFbaDelivery(tccFbaCancelItem.getBidFbaDelivery())
//					.setDelUserId(ShiroUtils.getUserId())
//					.setShipmentState(tccFbaCancelItem.getShipmentState())
//					.setStatus(1);
//			tccFbaCancelDelInfoMapper.insert(tccFbaCancelDelInfo);
//		}
//
//		//删除取消单信息
//		tccFbaCancelMapper.deleteTrue(entity.getId());
//		return R.ok();
//	}
//
//
//
//
//	/**
//	 * 参数验证
//	 */
//	public String checkParamsDoCancel(Map<String, Object> params, Long menuId) throws Exception {
//		//获取pc字段数据
//		List<YsCol> listField = new YsCol()
//				.where("A.MenuId = "+menuId)
//				.setOrderby("A.SortNo ASC")
//				.queryList();
//		//验证必填字段的非空；其他字段的长度限制、类型
//		String backMsg = checkUtil.checkTableColLengthAndDataType("TCC_FbaCancel",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);
//		return backMsg;
//	}
//
//






}
